package com.weibo.click;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.KeyStroke;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * 本class的作用是实现一个简易的Http服务器， 监听来自Firefox发送的对话框坐标和message等信息，然后强制把信息模拟发送给FF
 * 
 * @author Administrator
 * 
 */
public class localHttpLisenerImg {
	private int port;
	private java.util.Timer timer = null;
    private static String[] str=new String[378];
	private static  final AtomicInteger msgNum=new AtomicInteger(0);

	public localHttpLisenerImg() {
	}

	public localHttpLisenerImg(int port) {
		this.port = port;
	}

	public void start() {
		try {
		    InetSocketAddress address = new InetSocketAddress("127.0.0.1", port);
			HttpServer server = HttpServer.create(address, 0);
			ClipboardUtils clip=new ClipboardUtils();
			//clip.clickFireFoxLogout();
			
			server.createContext("/", new HttpHandler() {
				public void handle(HttpExchange he) {
					try {
						String ip = he.getRemoteAddress().getAddress().getHostAddress();
						//System.out.println("http消息发送的来源ip是："+ip);
						InputStream input_stream = he.getRequestBody();
						Headers paramHeaders = he.getRequestHeaders();
						Iterator params = paramHeaders.keySet().iterator();
						while (params.hasNext()) {
							String key = (String) params.next();
							String value = paramHeaders.getFirst(key);
							//System.out.println("Key  = " + key + "--- Value = "+ value);
						}
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(input_stream));
						StringBuilder str_builder = new StringBuilder();

						String line = null;
						while ((line = reader.readLine()) != null) {
							str_builder.append(line );
						}
						String qStr=str_builder.toString();
						//int len=qStr.length();
						//qStr=qStr.substring(0,len-2);//去掉结尾的\n符号
						System.out.println("send parameters string is:  "+ qStr);
						QueryString qs = new QueryString(qStr);
						if(qStr.contains("msg")){
						   handleMsg(qs);
						}else if(qStr.contains("method=logout")){
						   handleLogout(qs);
						}else if(qStr.contains("method=login")){
						   handleLogin(qs);
						}else if(qStr.contains("action=")){
						   handleClickAction(qs);
						}
						// 登录，
						String ret = "OK";
						he.sendResponseHeaders(200,ret.getBytes("utf-8").length);
						OutputStream os = he.getResponseBody();
						os.write(ret.getBytes());
						os.close();
					} catch (Exception e) {
						System.out.println("handle Exception");
						e.printStackTrace();
					}

				}

				private void handleClickAction(QueryString qs) {
					try {
						Robot robot = new Robot();
						String action = qs.getParameter("action");
						int x=Integer.parseInt(qs.getParameter("xPos"));
						int y=Integer.parseInt(qs.getParameter("yPos"));
						if(action.equals("clickPosWithMsg")){ //点击特定位置，并且传送真相消息
							String msg=qs.getParameter("msg");
							mouseMoveAndClick(robot, x, y);
							this.type(robot, msg);
						}else if(action.equals("clickPosImg")){
							String imgPath="c:/java/images";
							FilenameFilter filter = new FilenameFilter() { 
							    public boolean accept(File dir, String name) { 
							        return name.endsWith(".jpg"); 
							    } 
							}; 
							 
							File folder = new File(imgPath); 
							File[] listOfFiles = folder.listFiles(filter); 
							//计算有多少个可以使用的images文件，随机选择一个序号
							int seq=(int) (System.currentTimeMillis() %  listOfFiles.length);
							mouseMoveAndClick(robot, x, y);
							robot.delay(450);
							//把image文件路径复制到ClipBoard中！
							String file="c:\\java\\images\\ja"+seq+".jpg";
							if(seq<=9){
								file="c:\\java\\images\\ja0"+seq+".jpg";
							}else if(seq==0){
								file="c:\\java\\images\\ja01" +
										".jpg";
							}
							StringSelection stsel = new StringSelection(file);
					        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
					        
					 		robot.delay(163);
							robot.keyPress(KeyEvent.VK_CONTROL);
						    robot.delay(57);
							robot.keyPress(KeyEvent.VK_V);
						    robot.delay(111);
							robot.keyRelease(KeyEvent.VK_V);
						    robot.delay(45);
							robot.keyRelease(KeyEvent.VK_CONTROL);
						    robot.delay(357);
							robot.keyPress(KeyEvent.VK_ENTER);
					 		robot.delay(163);
							robot.keyRelease(KeyEvent.VK_ENTER);
						}else if(action.equals("clickPos")){
							mouseMoveAndClick(robot, x, y);
						}
					} catch (AWTException e) {
						e.printStackTrace();
					}
					
				}

				/**
				 * @param qs
				 */
				private void handleMsg(QueryString qs) {
					String msg = qs.getParameter("msg");
					int seq=msgNum.incrementAndGet();
					ClipboardUtils clip = new ClipboardUtils();
					//System.out.println("模拟键盘输入行为，发送真相短消息......"+ msg);
					clip.clickFireFox(msg);
				}
				
				private void handleLogout(QueryString qs) {
					ClipboardUtils clip = new ClipboardUtils();
					System.out.println("模拟键盘输入行为，handleLogout...");
					clip.clickFireFoxLogout();
				}
				private void handleLogin(QueryString qs) {
					ClipboardUtils clip = new ClipboardUtils();
					String user=qs.getParameter("user");
					String pass=qs.getParameter("pass");
					String verify=qs.getParameter("verify");
					System.out.println("模拟键盘输入行为，handleLogin...");
					clip.clickFireFoxLogin(user,pass,verify);
				}
				protected  void type(Robot robot,String s)
				  {
				    byte[] bytes;
					try {
						bytes = s.getBytes("UTF-8");
					    for (byte b : bytes){
					        int code = b;
					        //System.out.print(" Key Code="+code+";");
					        // keycode only handles [A-Z] (which is ASCII decimal [65-90])
					        if (code > 96 && code < 123){
					    	  code = code - 32;
					        }
						    robot.delay(5);
						    robot.keyPress(code);
						    robot.delay(4);
						    robot.keyRelease(code);
					    }//FOR
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				  }

				/* 鼠标移动，并且20毫秒以后点击对应的坐标 */
				protected void mouseMoveAndClick(Robot robot,int x, int y) {
					robot.mouseMove(x, y);
					robot.delay(945);
					robot.mousePress(KeyEvent.BUTTON1_MASK);
					robot.delay(22);
					robot.mouseRelease(KeyEvent.BUTTON1_MASK);// 松开鼠标左键
				}
				private void mouseMoveAndDoubleClick(Robot robot,int x, int y) {
					robot.mouseMove(x, y);
					robot.delay(845);
					robot.mousePress(KeyEvent.BUTTON1_MASK);
					robot.delay(90);
					robot.mouseRelease(KeyEvent.BUTTON1_MASK);// 松开鼠标左键
					robot.delay(110);
					robot.mousePress(KeyEvent.BUTTON1_MASK);
					robot.delay(119);
					robot.mouseRelease(KeyEvent.BUTTON1_MASK);// 松开鼠标左键
				}

			});
			server.start();
			System.out.println("Monitoring " + port + " port");
		} catch (Exception e) {
			System.out.println("localHttpLisener Exception");
			boolean jv;
			try {
				jv = ControlUtils.isProcessRunging("java.exe");
				if(jv){
					System.out.println("JDK running，Killing it");
					ControlUtils.killJAVA();	
				}
			} catch (Exception e1) {
				System.out.println("JDK running，Killing it");
				//e1.printStackTrace();
			}
			System.out.println("Http local server start Exception!");
			//e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		//truthArrayInit();
		//ControlUtils.killFirefox();
		new localHttpLisenerImg(9988).start();
	}

}
